package com.ruoyi.common.utils.shopping;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sun.org.apache.xpath.internal.operations.Bool;
import jdk.nashorn.internal.parser.Token;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class JwtUtil {


    private static String s = "avcsddd";

    public static String getToken(Map<String,String> param, Long mills){
        JWTCreator.Builder builder = JWT.create().withHeader(new Hashtable<>());
        for (String key : param.keySet()) {
            builder.withClaim(key,  param.get(key));
        }

        if(mills!=null){
            builder.withExpiresAt(new Date(System.currentTimeMillis() + mills));
        }
        return builder.sign(Algorithm.HMAC256(s));
    }
    public static DecodedJWT vailToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(s)).build().verify(token);
        return verify;
    }

    public static String getParam(DecodedJWT decodedJWT,String key) {
        return decodedJWT.getClaim(key).asString();
    }

    public static Long isExpire(DecodedJWT decodedJWT){
        if(decodedJWT.getExpiresAt() == null){
            return -1L;
        }
        return decodedJWT.getExpiresAt().getTime();
    }

    public static void main(String[] args) {
        Map<String ,String> stringObjectMap = new HashMap<>();
        stringObjectMap.put("username","keiom");
        stringObjectMap.put("password","abc123");
        String token = getToken(stringObjectMap, 10L);
        System.out.println(token);
        System.out.println(getParam(vailToken(token),"username"));
        System.out.println(isExpire(vailToken(token)));
    }
}
